/** \file Options.cc
 * Definitions for the class Options.cc
 *
 * (C) Copyright  by Semih Cemiloglu
 * All rights reserved, see COPYRIGHT file for details.
 *
 * $Id$
 *
 *
 */

#include "Options.hh"
#include <QTextStream>
#include <QtDebug>


using namespace TC;


Options::Options(int argc, const char** argv)
{
  for (int i=0; i<argc; ++i) {
		m_args += QString(argv[i]);
	}
}

Options::Options(QStringList args)
{
  m_args.append(args);
}

Options::~Options()
{
}

Options& Options::addOption(const Option& opt)
{
  m_optSpecs.push_back(opt);
  if(!opt.m_def.isEmpty()) {
    m_optVals[opt.m_name] = opt.m_def;
  }
  return *this;
}

void Options::clear()
{
  m_args.clear();
  m_optVals.clear();
}


void Options::printUsage(QTextStream& out)
{
}

void Options::setArgs(QStringList args)
{
  m_args.append(args);  
}

bool Options::parse()
{
  bool rv = true;
  bool dp = false; // debug parsing

  // double dash
  QRegExp d_dash("--([\\w-]+)=?([^=]*)");
  // single dash
  QRegExp s_dash("-(\\w+)");
  QString arg;

  for(int i=0; i<m_args.size(); ++i) {
    arg = m_args.at(i);
    if(dp) qDebug() << arg;

    if(arg == "--") break; // no more parsing
    
      if(d_dash.exactMatch(arg)) {
        if(dp) qDebug() << "--" << d_dash.capturedTexts();
        QString fkey = d_dash.cap(1);
        QString fval = d_dash.cap(2);
        foreach(const Option& opt, m_optSpecs) {
          if(fkey == opt.m_name)
            m_optVals.insert(fkey, fval);
        }
        continue;
      }
      else {
        if(dp) qDebug() << "e--" << d_dash.capturedTexts();
      }


      if(s_dash.exactMatch(arg)) {
        if(dp) qDebug() << "-" << s_dash.capturedTexts();
        QString fkeys = s_dash.cap(1);
        foreach(const Option& opt, m_optSpecs) {
          if(fkeys.contains(opt.m_letter))
            m_optVals.insert(opt.m_name, QString());
        }
        continue;
      }
      else {
        if(dp) qDebug() << "e-" << s_dash.capturedTexts();
      }
      
  } // end for 

  return rv;
}
  
